package com.hpjz.common.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import lombok.extern.log4j.Log4j;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;

/**
 * 
 * 项目日期处理类
 * 
 * @author 陈保毕
 *
 */
@Log4j
public class DateUtil {
	private DateUtil(){}
	
	 /**
	  * 清空日期中的分秒、毫秒，仅留年月日
	  * 
	  * @param date
	  * @return
	  */
	 public static Date truncate(Date date){
		 return DateUtils.truncate(date, Calendar.DATE);
	 }
	 
	
	
	 /**
	  * 将日期字符串转化成日期类型
	  * @param str
	  * @return
	  */
	 public static Date parse(String str){
		  Date date = null;
	      String[] parsers =
	          new String[] { "yyyy'-'DDD", "yyyy'-'MM'-'dd", "yyyyMMdd", "yyyy'-'MM'-'dd HH:mm:ss",
	              "yyyy'-'MM'-'dd HH:mm:ss.SSS", "yyyy'-'MM'-'dd HH:mm" };
	      
	      try {
	    	  if (StringUtils.isEmpty(str)) {
	    		  return date;
	    	  }
			date = DateUtils.parseDate(str, parsers);
    		} catch (ParseException e) {
    			log.error("日期格式错误："+str);
		}
	      return date;
	  }
	 
	 /**
	  * 将日期类型转化为字符串
	  * @return
	  */
	 public static String dateToStr(Date date){
		 String dateStr = null;
		  if (date!=null) {
			 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			 dateStr = format.format(date);
 	      }
		 return dateStr;
	 }
	 
}
